
// Created by carolsail 
const { ccclass, property } = cc._decorator;

import { ENUM_AUDIO_CLIP, ENUM_GAME_MODE, ENUM_GAME_STATUS, ENUM_UI_TYPE } from "../Enum";
import { StaticInstance } from "../StaticInstance";
import Car from "../game/Car";
import Level from "../game/Level";
import Player, { PLAYER_STATE } from "../game/Player";
import AudioManager from "./AudioManager";
import DataManager, { GAME_DATA } from "./DataManager";
import PoolManager from "./PoolManager";
import SdkManager from "./SdkManager";
import ToastManager from "./ToastManager";

@ccclass
export default class GameManager extends cc.Component {

    stage: cc.Node = null
    levelComp: Level = null

    onLoad() {
        StaticInstance.setGameManager(this)
        this.stage = cc.find('Stage', this.node)

    }

    onDestroy() { }

    // 开始游戏
    onGameStart() {
        DataManager.instance.reset()
        this.initGame()
    }

    // 游戏结束
    onGameOver(ui: ENUM_UI_TYPE) {
        DataManager.instance.status = ENUM_GAME_STATUS.UNRUNING
        if (StaticInstance.uiManager.isActive(ENUM_UI_TYPE.EXIT)) StaticInstance.uiManager.toggle(ENUM_UI_TYPE.EXIT, false)
        if (ui == ENUM_UI_TYPE.LOSE) {
            AudioManager.instance.playSound(ENUM_AUDIO_CLIP.LOSE)
            this.scheduleOnce(() => {
                StaticInstance.uiManager.toggle(ENUM_UI_TYPE.LOSE)
            }, 0.2)
        } else if (ui == ENUM_UI_TYPE.WIN) {
            AudioManager.instance.playSound(ENUM_AUDIO_CLIP.WIN)
            // 关卡+1
            DataManager.instance.level += 1
            if (DataManager.instance.level > DataManager.instance.levelMax) {
                DataManager.instance.levelMax = DataManager.instance.level
                // 子域排行榜
                SdkManager.instance.setRank(DataManager.instance.level)
            }
            DataManager.instance.save()
            this.scheduleOnce(() => {
                StaticInstance.uiManager.toggle(ENUM_UI_TYPE.WIN)
            }, 0.2)
        }
    }

    onGameOverPk(isWin: boolean) {
        DataManager.instance.status = ENUM_GAME_STATUS.UNRUNING
        StaticInstance.uiManager.setMainAi(false)
        if (StaticInstance.uiManager.isActive(ENUM_UI_TYPE.EXIT_PK)) StaticInstance.uiManager.toggle(ENUM_UI_TYPE.EXIT_PK, false)
        if (isWin) {
            AudioManager.instance.playSound(ENUM_AUDIO_CLIP.WIN)
            DataManager.instance.countWin += 1
        } else {
            AudioManager.instance.playSound(ENUM_AUDIO_CLIP.LOSE)
            DataManager.instance.countLose += 1
        }
        DataManager.instance.save()
        StaticInstance.uiManager.setOverLabel(isWin)
        this.scheduleOnce(() => {
            StaticInstance.uiManager.toggle(ENUM_UI_TYPE.OVER)
        }, 0.5)
    }

    // 技能
    onGameSkill(index: number) {
        if (DataManager.instance.status == ENUM_GAME_STATUS.UNRUNING) return
        const theMovePlayer = this.levelComp.hasPlayer(PLAYER_STATE.MOVE)
        if (theMovePlayer) {
            ToastManager.instance.show('人员移动中，请稍后~', { gravity: 'TOP', bg_color: cc.color(226, 69, 109, 255) })
            return
        }
        if (index == 0) {
              // 使用防抖后的 showVideoAd
              SdkManager.instance.showVideoAd( (msg: string) => {
                    console.log('技能换位看广后');
                    if (!SdkManager.instance.getPlatform()) {
                        ToastManager.instance.show(msg, { gravity: 'TOP', bg_color: cc.color(102, 202, 28, 255) });
                    }
                    StaticInstance.uiManager.setMainSkillTip(true);
                },
                (msg: string) => {
                    ToastManager.instance.show(msg, { gravity: 'TOP', bg_color: cc.color(226, 69, 109, 255) });
                }
            );
        } else if (index == 1) {
            // 消除
            console.log('技能消除')
            const carNodeRuning = this.levelComp.getReadyCarRuning()
            if (carNodeRuning) {
                ToastManager.instance.show('车辆移动中，请稍后~', { gravity: 'TOP', bg_color: cc.color(226, 69, 109, 255) })
                return
            }
            const car = this.levelComp.getTargetCar()
            if (!car) {
                ToastManager.instance.show('车辆移动中，请稍后~', { gravity: 'TOP', bg_color: cc.color(226, 69, 109, 255) })
                return
            }
           
            SdkManager.instance.showVideoAd((msg: string) => {
                console.log('技能消除看广后')
                if (index != 1) {
                    console.log('点击不是技能消除')
                    return
                }
                if (!SdkManager.instance.getPlatform()) {
                    ToastManager.instance.show(msg, { gravity: 'TOP', bg_color: cc.color(102, 202, 28, 255) })
                }
                AudioManager.instance.playSound(ENUM_AUDIO_CLIP.SKILL_DELETE)
                const carComp = car.getComponent(Car)
                const playerArr = this.levelComp.playerRoot.children
                // 移除人员
                let delPlayer = []
                for (let i = 0; i < playerArr.length; i++) {
                    const player = playerArr[i]
                    const playerComp = player.getComponent(Player)
                    if (playerComp.colorIndex == carComp.colorIndex) {
                        if (delPlayer.length < GAME_DATA.COMBINE - carComp.playerNums) {
                            delPlayer.push(player)
                            if (delPlayer.length == GAME_DATA.COMBINE) break
                        }
                    }
                }
                DataManager.instance.levelPlayerClear += delPlayer.length
                let other = GAME_DATA.COMBINE - delPlayer.length - carComp.playerNums
                if (other > 0) {
                    DataManager.instance.levelPlayerClear += other
                    // 扣后备数据
                    while (other > 0) {
                        other -= 1
                        const index = this.levelComp.playerColorIndexArr.findIndex(cindex => cindex == carComp.colorIndex)
                        this.levelComp.playerColorIndexArr.splice(index, 1)
                        // console.log('删除', index)
                    }
                }
                // 删除人员(需要补位)
                if (this.levelComp.playerColorIndexArr.length && delPlayer.length) {
                    const delPlayerPos = []
                    delPlayer.forEach(player => {
                        const playerComp = player.getComponent(Player)
                        if (playerComp.posY >= 2) delPlayerPos.push({ x: playerComp.posX, y: playerComp.posY })
                        player.removeFromParent()
                    })
                    // 开始补位
                    DataManager.instance.isCovering = true
                    this.levelComp.onPlayerCover(delPlayerPos)
                } else {
                    delPlayer.forEach(player => {
                        const playerComp = player.getComponent(Player)
                        player.removeFromParent()
                        this.levelComp.resetMapPoints(playerComp.posX, playerComp.posY)
                    })
                }
                StaticInstance.uiManager.setMainPlayerNum()
                // 车移走
                carComp.setMove(GAME_DATA.CAR_POSX[3], GAME_DATA.CAR_POSX[4])
                
            }, (msg: string) => {
                ToastManager.instance.show(msg, { gravity: 'TOP', bg_color: cc.color(226, 69, 109, 255) })
            })
        } else if (index == 2) {
            // 加一格
            console.log('技能加一格')
            const boad = this.levelComp.getLockBoard()
            if (boad) {
                SdkManager.instance.showVideoAd((msg: string) => {
                    console.log('技能加一格看广后')
                    if (!SdkManager.instance.getPlatform()) {
                        ToastManager.instance.show(msg, { gravity: 'TOP', bg_color: cc.color(102, 202, 28, 255) })
                    }
                    AudioManager.instance.playSound(ENUM_AUDIO_CLIP.UNLOCK)
                    DataManager.instance.targetMarkLimit += 1
                    boad.getChildByName('locked').removeFromParent()
                }, (msg: string) => {
                    ToastManager.instance.show(msg, { gravity: 'TOP', bg_color: cc.color(226, 69, 109, 255) })
                })
            } else {
                ToastManager.instance.show('槽位已满~', { gravity: 'TOP', bg_color: cc.color(226, 69, 109, 255) })
            }
        }
    }

    // 初始化游戏
    async initGame() {
        DataManager.instance.status = ENUM_GAME_STATUS.UNRUNING
        this.stage.removeAllChildren()
        const levelNode = PoolManager.instance.getNode('Level', this.stage)
        this.levelComp = levelNode.getComponent(Level)
        this.levelComp.init()
        StaticInstance.uiManager.setMainPlayerNum(true)
        StaticInstance.uiManager.setMainCurrentLevel()
        StaticInstance.uiManager.setMainSkillTip(false)
        StaticInstance.uiManager.setMainAi(true)
        DataManager.instance.status = ENUM_GAME_STATUS.RUNING
        await StaticInstance.fadeManager.fadeOut()
    }

    // 获取levelComp
    getLevelComp() {
        return this.levelComp
    }
}
